package com.bootdo.app.service.impl;

import com.bootdo.app.common.aop.exception.ExceptionEnum;
import com.bootdo.app.common.aop.exception.MiniprogramException;
import com.bootdo.app.common.utils.ContextHandlerUtil;
import com.bootdo.app.enums.GroupBuyingStatusEnum;
import com.bootdo.app.service.UserGroupBuyService;
import com.bootdo.app.vo.miniprogram.GroupBuyJoinerVo;
import com.bootdo.app.vo.miniprogram.UserGroupBuyVo;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.system.domain.TbGroupBuying;
import com.bootdo.system.domain.TbGroupBuyingExample;
import com.bootdo.system.domain.TbGroupBuyingExample.Criteria;
import com.bootdo.system.domain.TbGroupBuyingJoiner;
import com.bootdo.system.domain.TbGroupBuyingJoinerExample;
import com.bootdo.system.domain.TbStock;
import com.bootdo.system.domain.TbSvip;
import com.bootdo.system.mapper.TbGroupBuyingJoinerMapper;
import com.bootdo.system.mapper.TbGroupBuyingMapper;
import com.bootdo.system.mapper.TbStockMapper;
import com.bootdo.system.mapper.TbSvipMapper;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @auther: Along
 * @description: 用户拼团业务
 */
@Slf4j
@Service
public class UserGroupBuyServiceImpl implements UserGroupBuyService {

    @Autowired
    private TbGroupBuyingMapper groupBuyingMapper;
    @Autowired
    private TbGroupBuyingJoinerMapper groupBuyingJoinerMapper;
    @Autowired
    private TbStockMapper tbStockMapper;
    
    @Autowired
    private TbSvipMapper sm;
	
    
    /**
     * 创建拼团
     * @param goodsId 商品id
     * @return
     */
    @Override
    public UserGroupBuyVo makeGroupBuy(String goodsId) {
        String currentUserId = ContextHandlerUtil.getCurrentUserId();
        String sid = ContextHandlerUtil.getSID();
        // 查询是否已经创建过拼团信息，如果已经创建过，则返回已经创建的拼团信息，否则创建拼团信息
        UserGroupBuyVo userGroupBuyVo = groupBuyingMapper.selectGroupBuyLeaderInfo(Integer.valueOf(currentUserId), sid, goodsId);
        if(userGroupBuyVo != null){
        	//查询日期
//        	 List<TbGroupBuying> listByUser = groupBuyingMapper.getListByUser(Integer.valueOf(currentUserId),DateUtils.format3(new Date()));
//             if(listByUser.size() > 0) {
//             	return null;
//             }
        	TbStock selectByPrimaryKey = tbStockMapper.selectByPrimaryKey(Integer.valueOf(goodsId));
        	if(selectByPrimaryKey != null) {
        		Double money = getDouble2String(selectByPrimaryKey.getMoney());
        		Double stock = getDouble2String(selectByPrimaryKey.getStock());
        		userGroupBuyVo.setPrice((money+stock)+"");
        		TbSvip byStoId = getByStoId(selectByPrimaryKey.getId());
            	userGroupBuyVo.setGoodsName(byStoId.getTitle());
            	userGroupBuyVo.setProductClass(byStoId.getProductclass());
        	}
        	
            Date endDateTime = userGroupBuyVo.getEndDateTime();
            Date now = Calendar.getInstance().getTime();
            if(now.compareTo(endDateTime) < 0){ // 未过期
                List<GroupBuyJoinerVo> groupBuyJoinerVos = groupBuyingJoinerMapper.selectJoiners(userGroupBuyVo.getId());
                userGroupBuyVo.setJoiners(groupBuyJoinerVos);
                return userGroupBuyVo;
            }else{ // 过期
                // 更新当前拼团状态 并且创建新的拼团
                groupBuyingMapper.updateByPrimaryKeySelective(TbGroupBuying.updateStatus(userGroupBuyVo.getId(),GroupBuyingStatusEnum.EXPIRE.getStatus()));
            }
        }
        // 创建拼团
        TbGroupBuying tbGroupBuying = TbGroupBuying.makeGroupBuy(Integer.valueOf(currentUserId), sid, goodsId);
        groupBuyingMapper.insert(tbGroupBuying);
        userGroupBuyVo = groupBuyingMapper.selectGroupBuyLeaderInfo(Integer.valueOf(currentUserId), sid, goodsId);
        List<GroupBuyJoinerVo> groupBuyJoinerVos = groupBuyingJoinerMapper.selectJoiners(tbGroupBuying.getId());
        TbStock selectByPrimaryKey = tbStockMapper.selectByPrimaryKey(Integer.valueOf(goodsId));
    	if(selectByPrimaryKey != null) {
    		Double money = getDouble2String(selectByPrimaryKey.getMoney());
    		Double stock = getDouble2String(selectByPrimaryKey.getStock());
    		userGroupBuyVo.setPrice((money+stock)+"");
    		
    		TbSvip byStoId = getByStoId(selectByPrimaryKey.getId());
        	userGroupBuyVo.setGoodsName(byStoId.getTitle());
        	userGroupBuyVo.setProductClass(byStoId.getProductclass());
    	}
        userGroupBuyVo.setJoiners(groupBuyJoinerVos);
        return userGroupBuyVo;
    }

    
    public TbSvip getByStoId(Integer id) {
		TbStock selectByPrimaryKey = tbStockMapper.selectByPrimaryKey(id);
		if(selectByPrimaryKey != null) {
			String svipId = selectByPrimaryKey.getSvipId();
			return sm.selectByPrimaryKey(Integer.valueOf(svipId));
		}
		return null;
	}
    /**
     * 加入拼团
     * @param groupBuyId 拼团id
     * @return
     */
    @Override
    public UserGroupBuyVo joinGroupBuy(Integer groupBuyId,String currentUserId) {
        // 判断拼团当前状态
        TbGroupBuying groupBuying = groupBuyingMapper.selectByPrimaryKey(groupBuyId);
       
        if(groupBuying == null){
           return null;
        }
        Integer status = groupBuying.getStatus();
        if(!Objects.equals(status,GroupBuyingStatusEnum.MAKE.getStatus())){
        	return null;
        }
        Date now = Calendar.getInstance().getTime();
        if(now.compareTo(groupBuying.getEndDateTime()) > 0){ // 过期
            groupBuyingMapper.updateByPrimaryKeySelective(TbGroupBuying.updateStatus(groupBuying.getId(),GroupBuyingStatusEnum.EXPIRE.getStatus()));
            return null;
        }
        // 判断 是否是自己的拼团
        if(!currentUserId.equals(groupBuying.getCreateUserId().toString())){ // 不是自己的拼团
            // 查询是否加入过该拼团
            TbGroupBuyingJoinerExample example = new TbGroupBuyingJoinerExample();
            TbGroupBuyingJoinerExample.Criteria criteria = example.createCriteria();
            criteria.andJoinUserIdEqualTo(Integer.valueOf(currentUserId));
            criteria.andGroupBuyIdEqualTo(groupBuyId);
            List<TbGroupBuyingJoiner> tbGroupBuyingJoiners = groupBuyingJoinerMapper.selectByExample(example);
            if(tbGroupBuyingJoiners.size() >= 8) {
            	return null;
            }
            if(tbGroupBuyingJoiners == null || tbGroupBuyingJoiners.isEmpty()){ // 说明从未加入过该拼团
                // 加入拼团
                TbGroupBuyingJoiner joiner = new TbGroupBuyingJoiner();
                joiner.setJoinUserId(Integer.valueOf(currentUserId));
                joiner.setGroupBuyId(groupBuyId);
                groupBuyingJoinerMapper.insert(joiner);
            }
        }
        // 查询拼团信息
        UserGroupBuyVo userGroupBuyVo = groupBuyingMapper.selectGroupBuyLeaderInfo(groupBuying.getCreateUserId(), groupBuying.getSid(), groupBuying.getGoodsId());
        List<GroupBuyJoinerVo> groupBuyJoinerVos = groupBuyingJoinerMapper.selectJoiners(userGroupBuyVo.getId());
        if(groupBuyJoinerVos.size() > 8) {
        	return null;
        }
        userGroupBuyVo.setJoiners(groupBuyJoinerVos);
        return userGroupBuyVo;
    }

    /**
     * 取消拼团
     */
    @Override
    public void cancelGroupBuy(Integer groupBuyId) {
        TbGroupBuying groupBuying = groupBuyingMapper.selectByPrimaryKey(groupBuyId);
        if(groupBuying == null){
            throw new MiniprogramException(ExceptionEnum.MINI_PROGRAM_GROUP_BUY_NULL);
        }
        if(Objects.equals(groupBuying.getStatus(),GroupBuyingStatusEnum.MAKE.getStatus())){
            groupBuyingMapper.updateByPrimaryKeySelective(TbGroupBuying.updateStatus(groupBuyId, GroupBuyingStatusEnum.CANCEL.getStatus()));
        }
    }
    
    private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}

	@Override
	public void endGroupBuy(String goodsId) {
		
		String currentUserId = ContextHandlerUtil.getCurrentUserId();
        String sid = ContextHandlerUtil.getSID();
        System.out.println(goodsId+"===="+currentUserId+"======"+sid);
        if(currentUserId == null || sid == null) {
        	return;
        }
        // 查询是否已经创建过拼团信息，如果已经创建过，则返回已经创建的拼团信息，否则创建拼团信息
        UserGroupBuyVo userGroupBuyVo = groupBuyingMapper.selectGroupBuyLeaderInfo(Integer.valueOf(currentUserId), sid, goodsId);
        if(userGroupBuyVo == null){
        	return;
        }
        if(Objects.equals(userGroupBuyVo.getStatus(),GroupBuyingStatusEnum.MAKE.getStatus())){
            groupBuyingMapper.updateByPrimaryKeySelective(TbGroupBuying.updateStatus(userGroupBuyVo.getId(), GroupBuyingStatusEnum.END.getStatus()));
        }
	}

	@Override
	public boolean statusGroupBuy(String groupBuyId) {
		String currentUserId = ContextHandlerUtil.getCurrentUserId();
        String sid = ContextHandlerUtil.getSID();
        // 查询是否已经创建过拼团信息，如果已经创建过，则返回已经创建的拼团信息，否则创建拼团信息
        UserGroupBuyVo userGroupBuyVo = groupBuyingMapper.selectGroupBuyLeaderInfo(Integer.valueOf(currentUserId), sid, groupBuyId);
        if(userGroupBuyVo != null) {
        	return true;
        }
		return false;
	}

	@Override
	public TbGroupBuying getByGoodsId(String goodsId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TbGroupBuying> getListByUser(Integer userId,String month) {
		return groupBuyingMapper.getListByUser(userId,month);
	}

	@Override
	public List<TbGroupBuying> list(Map<String, Object> map) {
		return groupBuyingMapper.list(map);
	}

	@Override
	public int count(Map<String, Object> map) {
		return groupBuyingMapper.count(map);
	}

	@Override
	public int yqrNum(Integer groupBuyId) {
        List<GroupBuyJoinerVo> groupBuyJoinerVos = groupBuyingJoinerMapper.selectJoiners(groupBuyId);
        if(groupBuyJoinerVos != null) {
        	return groupBuyJoinerVos.size();
        }
		return 0;
	}

	@Override
	public List<GroupBuyJoinerVo> getYqUser(Integer groupBuyId) {
		return groupBuyingJoinerMapper.selectJoiners(groupBuyId);
	}
}
